package leetcode.array;

/**
 * @Description: https://leetcode.cn/problems/spiral-matrix-ii/description/
 * @Author Ammar
 * @Create 2023/8/3 11:47
 */
public class _59_螺旋矩阵II {
    public int[][] generateMatrix(int n) {
        if (n == 1) return new int[][]{new int[]{1}};
        int[][] nums = new int[n][n];
        int top = 0;
        int left = 0;
        int right = n - 1;
        int bottom = n - 1;
        int count = 1;
        while(top <= bottom) {
            for (int i = left; i <= right; i++) {
                nums[top][i] = count;
                count++;
            }
            top++;
            if (top > bottom) break;
            for (int i = top; i <= bottom; i++) {
                nums[i][right] = count;
                count++;
            }
            right--;
            if (left > right) break;
            for (int i = right; i >= left; i--) {
                nums[bottom][i] = count;
                count++;
            }
            bottom--;
            if (top > bottom) break;
            for (int i = bottom; i >= top; i--) {
                nums[i][left] = count;
                count++;
            }
            left++;
            if (left > right) break;
        }
        return nums;
    }
}
